package com.sxt.test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.junit.Test;

import com.sxt.entity.City;
import com.sxt.entity.Student;
import com.sxt.entity.Teacher;
import com.sxt.entity.User;
import com.sxt.factory.HibernateSessionFactory;

public class CaseCade {
	/**
	 * 级联添加-主控放为many
	 */
	@Test
	public void test1() {
		Session session = HibernateSessionFactory.getSession();
		City city = new City("江西");
		User user = new User(null, "陈凯", 18, city);
		Transaction tx = session.beginTransaction();
		session.save(user);
		tx.commit();
		session.close();
	}
	
	/**
	 * 级联删除
	 */
	@Test
	public void test2() {
		Session session = HibernateSessionFactory.getSession();
		City city = (City) session.get(City.class, 4);
		Transaction tx = session.beginTransaction();
		session.delete(city);
		tx.commit();
		session.close();
	}
	
	/**
	 * 级联添加-主控方:one
	 */
	@Test
	public void test3() {
		Session session = HibernateSessionFactory.getSession();
		User user = new User(null, "张七招", 25, null);
		City city = new City("陕西");
		user.setCity(city);
		city.getUsers().add(user);
		Transaction tx = session.beginTransaction();
		session.save(city);
		tx.commit();
		session.close();
	}
	
	/**
	 * 多对多中间表级联添加
	 * 主控方为Teacher
	 */
	@Test
	public void test4() {
		Session session = HibernateSessionFactory.getSession();
		Teacher teacher = (Teacher) session.get(Teacher.class, 2);
		Student student1 = (Student) session.get(Student.class, 2);
		Student student2 = (Student) session.get(Student.class, 3);
		teacher.getStudents().add(student1);
		teacher.getStudents().add(student2);
		Transaction tx = session.beginTransaction();
		session.update(teacher);
		tx.commit();
		session.close();
	}
	
	/**
	 * 多对多中间表级联更新
	 */
	@Test
	public void test5() {
		Session session = HibernateSessionFactory.getSession();
		Teacher teacher2 = (Teacher) session.get(Teacher.class, 2);
		Teacher teacher1 = (Teacher) session.get(Teacher.class, 1);
		Student student = (Student) session.get(Student.class, 3);
		teacher2.getStudents().remove(student);
		teacher1.getStudents().add(student);
		Transaction tx = session.beginTransaction();
		session.update(teacher1);
		session.update(teacher2);
		tx.commit();
		session.close();
	}
	
	/**
	 * 多对多中间表级联删除
	 */
	@Test
	public void test6() {
		Session session = HibernateSessionFactory.getSession();
		Teacher teacher = (Teacher) session.get(Teacher.class, 1);
		Student student = (Student) session.get(Student.class, 3);
		teacher.getStudents().remove(student);
		Transaction tx = session.beginTransaction();
		session.update(teacher);
		tx.commit();
		session.close();
	}
}
